<template>
	<view class="container">
		<view class="form">
			<uni-forms :modelValue="formData">
				<uni-forms-item label="头像" name="headPic">
					<view class="avatar-upload" @click="chooseAvatar">
						<img v-if="formData.headPic" :src="`${BASE_URL}/${formData.headPic}`" class="avatar-img" mode="aspectFill" />
						<uni-icons v-else type="person" size="60"></uni-icons>
					</view>
				</uni-forms-item>
				<uni-forms-item label="昵称" name="nickName">
					<uni-easyinput v-model="formData.nickName"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="邮箱" name="email">
					<uni-easyinput disabled v-model="formData.email"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="验证码" name="captcha">
					<view class="captcha">
						<uni-easyinput v-model="formData.captcha"></uni-easyinput>
						<button :loading="isLoading" :disabled="isCounting" style="background-color: #ebf5ff" size="mini" type="primary" plain @click="sendCaptcha">
							{{ isCounting ? `重新发送(${count}s)` : '发送验证码' }}
						</button>
					</view>
				</uni-forms-item>
			</uni-forms>
			<button type="primary" @click="onSubmit">修改</button>
		</view>
	</view>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getInfo, sendUpdateUserInfoCaptcha, updateUserInfo } from '../../api/user';
import { BASE_URL } from '../../utils/system.js';

const formData = reactive({
	headPic: '',
	email: '',
	captcha: '',
	nickName: ''
});
const count = ref(30); // 倒计时秒数
const isCounting = ref(false); // 是否在倒计时中
const isLoading = ref(false);

const sendCaptcha = async () => {
	isLoading.value = true;
	const res = await sendUpdateUserInfoCaptcha({ address: formData.email });
	uni.showToast({
		title: res.data,
		icon: 'success',
		position: 'top'
	});
	isLoading.value = false;
	if (isCounting.value) return;
	isCounting.value = true;
	count.value = 30;

	const timer = setInterval(() => {
		count.value--;
		if (count.value <= 0) {
			clearInterval(timer);
			isCounting.value = false;
		}
	}, 1000);
};

const onSubmit = async () => {
	const res = await updateUserInfo({
		headPic: formData.headPic,
		nickName: formData.nickName,
		email: formData.email,
		captcha: formData.captcha
	});
	uni.showToast({
		title: '更改个人用户信息成功！',
		icon: 'none'
	});
	uni.switchTab({
		url: '/pages/user/user'
	});
};

const getUserInfo = async () => {
	const res = await getInfo();
	formData.headPic = res.data.headPic;
	formData.nickName = res.data.nickName;
	formData.email = res.data.email;
};

onLoad(() => {
	getUserInfo();
});

const chooseAvatar = () => {
	uni.chooseImage({
		count: 1, // 只选择一张图片
		sizeType: ['original', 'compressed'], // 可选择原图或压缩图
		sourceType: ['album', 'camera'], // 可选择相册或相机
		success: (res) => {
			// 获取图片路径并更新formData
			formData.headPic = res.tempFilePaths[0];
			uploadAvatar(res.tempFilePaths[0]);
		}
	});
};
const uploadAvatar = (filePath) => {
	uni.uploadFile({
		url: 'http://192.168.1.69:3005/user/upload', // 后端上传接口
		filePath, // 图片路径
		name: 'file', // 后端接收的字段名
		success: (uploadRes) => {
			const data = JSON.parse(uploadRes.data); // 解析返回的文件路径
			console.log('data', data);
			if (data) {
				const filePath = data.data.replace(/\\+/g, '/');
				formData.headPic = filePath; // 拼接完整的 URL
				console.log(formData.headPic);
				uni.showToast({
					title: '头像上传成功',
					icon: 'success'
				});
			} else {
				uni.showToast({
					title: '上传失败',
					icon: 'none'
				});
				formData.captcha = '';
			}
		},
		fail: (err) => {
			uni.showToast({
				title: '上传失败，请重试',
				icon: 'none'
			});
			console.error('上传失败', err);
		}
	});
};
</script>

<style lang="scss" scoped>
.container {
	.form {
		padding: 40rpx;
		.avatar-upload {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 200rpx;
			width: 200rpx;
			background-color: #f1f1f1;
			border-radius: 100rpx;
			cursor: pointer;
			position: relative;
			left: 50%;
			margin-left: -110rpx;
		}

		.avatar-img {
			width: 200rpx;
			height: 200rpx;
			border-radius: 50%;
		}
		.captcha {
			display: flex;
			button {
				margin-left: 20rpx;
			}
		}
	}
}
</style>
